package common.struct;

import com.alibaba.fastjson.JSONObject;
import common.struct.ConstantEnum.ResourceType;

import java.util.List;

public class ResourceConfig {
    public String name;
    public ResourceType type;
    public List<String> fields;
    JSONObject jo;

    public ResourceConfig(String name, ResourceType type, List<String> fields) {
        this.name = name;
        this.type = type;
        this.fields = fields;
    }

    public static ResourceConfig fromString(String json) {
        JSONObject jo =  JSONObject.parseObject(json);
        return fromJSONObject(jo);
    }

    public static ResourceConfig fromJSONObject(JSONObject jo) {
        String name = jo.getString("name");
        ResourceType type = ResourceType.fromString(jo.getString("type"));
        List<String> fields = null;
        try {
            fields = jo.getJSONArray("fields").toJavaList(String.class);
        } catch (Exception ignored) {}
        ResourceConfig resourceConfig = new ResourceConfig(name, type, fields);
        resourceConfig.jo = jo;
        return resourceConfig;
    }

    @Override
    public String toString() {
        if (jo != null) return jo.toJSONString();
        jo = new JSONObject();
        jo.put("name", name);
        jo.put("type", type.toString());
        jo.put("fields", fields);//TODO: check if this is correct
        return jo.toJSONString();
    }
}
